package com.ssm.blog.controller;

import com.github.pagehelper.PageInfo;
import com.ssm.blog.pojo.Role;
import com.ssm.blog.pojo.TreeNode;
import com.ssm.blog.service.MenuService;
import com.ssm.blog.service.RoleService;
import com.ssm.blog.util.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/role.html")
public class RoleController {
    @Autowired
    private RoleService roleService;

    @RequestMapping(params = "act=list")
    @ResponseBody
    public Map<String, Object> roleTable(Role role, Integer page, Integer rows) {
        PageInfo<Role> pageInfo = roleService.getRolePagerModel(role, page, rows);
        //key不可以改，页面上分页插件需要
        return JsonUtil.getDatagridPagerResult(pageInfo.getTotal(), pageInfo.getList());
    }

    @RequestMapping(params = "act=edit")
    @ResponseBody
    public Map<String, Object> edit(Role role) {
        if (role.getId() == null) {
            roleService.addRole(role);
        } else {
            roleService.updateRole(role);
        }
        return JsonUtil.getSuccessMessage("编辑成功", null);
    }

    @RequestMapping(params = "act=delete")
    @ResponseBody
    public Map<String, Object> delete(Integer id) throws Exception {
        roleService.deleteRole(id);
        return JsonUtil.getSuccessMessage("删除成功", null);
    }

    @Autowired
    private MenuService menuService;

    //加载所有菜单列表
    @RequestMapping(params = "act=menu_list")
    @ResponseBody
    public List<TreeNode> getAllMenu() {
        return menuService.getAllMenu();
    }

    //加载角色拥有的菜单
    @RequestMapping(params = "act=role_menu")
    @ResponseBody
    public List<Integer> getRoleMenu(Integer roleId) {
        return roleService.getRoleMenuIds(roleId);
    }

    @RequestMapping(params = "act=assign_menu")
    @ResponseBody
    public Map<String, Object> assignRoleMenu(Integer roleId, Integer[] menuIds) throws Exception {
        roleService.addRolePermission(roleId, menuIds);
        return JsonUtil.getSuccessMessage("分配权限成功", null);
    }
}
